#include "atom.h"
#include "atomqueue.h"
#include <stdint.h>
#include <stdlib.h>
#undef OK
#include "FreeRTOS.h"
#include "freertos/queue.h"



uint8_t atomQueueCreate(ATOM_QUEUE* qptr, uint8_t* buff_ptr, uint32_t unit_size, uint32_t max_num_msgs) {
    if (qptr == NULL || buff_ptr == NULL || unit_size == 0 || max_num_msgs == 0) {
        return ATOM_ERROR;
    }

    qptr->handle = (POINTER)xQueueCreate(max_num_msgs, unit_size);
    if (qptr->handle == NULL) {
        return ATOM_ERROR;
    }

    return ATOM_OK;
}

uint8_t atomQueueDelete(ATOM_QUEUE* qptr) {
    if (qptr == NULL || qptr->handle == NULL) {
        return ATOM_ERROR;
    }

    vQueueDelete((QueueHandle_t)qptr->handle);
    qptr->handle = NULL;

    return ATOM_OK;
}

uint8_t atomQueueGet(ATOM_QUEUE* qptr, int32_t timeout, uint8_t* msgptr) {
    if (qptr == NULL || msgptr == NULL) {
        return ATOM_ERROR;
    }

    TickType_t xTicksToWait;
    if (timeout < 0) {
        xTicksToWait = portMAX_DELAY;
    } else {
        xTicksToWait = timeout / portTICK_PERIOD_MS;
    }

    BaseType_t ret = xQueueReceive((QueueHandle_t)qptr->handle, msgptr, xTicksToWait);
    
    if ( ret == errQUEUE_EMPTY) {
        return ATOM_TIMEOUT;
    }else if (ret != pdPASS) {
        return ATOM_ERROR;
    }

    return ATOM_OK;
}

uint8_t atomQueuePut(ATOM_QUEUE* qptr, int32_t timeout, uint8_t* msgptr) {
    if (qptr == NULL || msgptr == NULL) {
        return ATOM_ERROR;
    }

    TickType_t xTicksToWait;
    if (timeout < 0) {
        xTicksToWait = portMAX_DELAY;
    } else {
        xTicksToWait = timeout / portTICK_PERIOD_MS;
    }

    BaseType_t ret = xQueueSend((QueueHandle_t)qptr->handle, msgptr, xTicksToWait);

    if ( ret == errQUEUE_EMPTY) {
        return ATOM_TIMEOUT;
    }else if (ret != pdPASS) {
        return ATOM_ERROR;
    }

    return ATOM_OK;
}